from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from models import DroneType, User
from schemas import DroneTypeCreate, DroneTypeUpdate, DroneTypeSchema, ResponseModel, PaginatedResponse
from api.deps import get_current_active_user, get_current_superuser

router = APIRouter()

@router.get("", response_model=ResponseModel[PaginatedResponse[DroneTypeSchema]])
def get_drone_types(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="类型名称搜索"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取无人机类型列表"""
    query = db.query(DroneType)
    
    if name:
        query = query.filter(DroneType.name.contains(name))
    
    # 计算总数
    total = query.count()
    
    # 分页
    drone_types = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=drone_types
        )
    )

@router.get("/{drone_type_id}", response_model=ResponseModel[DroneTypeSchema])
def get_drone_type(
    drone_type_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取无人机类型详情"""
    drone_type = db.query(DroneType).filter(DroneType.id == drone_type_id).first()
    if not drone_type:
        raise HTTPException(
            status_code=404,
            detail="无人机类型不存在"
        )
    
    return ResponseModel(data=drone_type)

@router.post("", response_model=ResponseModel[DroneTypeSchema])
def create_drone_type(
    drone_type_in: DroneTypeCreate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """创建无人机类型"""
    # 检查类型名是否已存在
    drone_type = db.query(DroneType).filter(DroneType.name == drone_type_in.name).first()
    if drone_type:
        raise HTTPException(
            status_code=400,
            detail="无人机类型名称已存在"
        )
    
    # 创建新无人机类型
    db_drone_type = DroneType(
        name=drone_type_in.name,
        description=drone_type_in.description,
        max_speed=drone_type_in.max_speed,
        max_payload=drone_type_in.max_payload,
        max_flight_time=drone_type_in.max_flight_time
    )
    
    db.add(db_drone_type)
    db.commit()
    db.refresh(db_drone_type)
    
    return ResponseModel(data=db_drone_type)

@router.put("/{drone_type_id}", response_model=ResponseModel[DroneTypeSchema])
def update_drone_type(
    drone_type_id: int,
    drone_type_in: DroneTypeUpdate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """更新无人机类型"""
    drone_type = db.query(DroneType).filter(DroneType.id == drone_type_id).first()
    if not drone_type:
        raise HTTPException(
            status_code=404,
            detail="无人机类型不存在"
        )
    
    # 检查类型名是否已存在（排除当前类型）
    if drone_type_in.name and drone_type_in.name != drone_type.name:
        existing_drone_type = db.query(DroneType).filter(DroneType.name == drone_type_in.name).first()
        if existing_drone_type:
            raise HTTPException(
                status_code=400,
                detail="无人机类型名称已存在"
            )
    
    # 更新字段
    update_data = drone_type_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(drone_type, field, value)
    
    db.commit()
    db.refresh(drone_type)
    
    return ResponseModel(data=drone_type)

@router.delete("/{drone_type_id}", response_model=ResponseModel[dict])
def delete_drone_type(
    drone_type_id: int,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """删除无人机类型"""
    drone_type = db.query(DroneType).filter(DroneType.id == drone_type_id).first()
    if not drone_type:
        raise HTTPException(
            status_code=404,
            detail="无人机类型不存在"
        )
    
    # 检查是否有无人机使用该类型
    if drone_type.drones:
        raise HTTPException(
            status_code=400,
            detail="该无人机类型正在被使用，无法删除"
        )
    
    db.delete(drone_type)
    db.commit()
    
    return ResponseModel(data={"message": "无人机类型删除成功"})